package grpc

import (
	"code/common/mysql"
	pb "code/common/protos"
	"context"
)

func (s *server) GetProblem(ctx context.Context, in *pb.IDRequest) (reply *pb.Problem, err error) {
	p := mysql.Problem{}
	err = mysql.Db.First(&p, in.ID).Error
	reply = &pb.Problem{
		ID:         uint32(p.ID),
		Name:       p.Name,
		CategoryId: uint32(p.CategoryId),
		Content:    p.Content,
		VerifyCode: p.VerifyCode,
	}
	return
}

func (s *server) GetCategories(ctx context.Context, in *pb.Empty) (reply *pb.Categories, err error) {
	cs := []mysql.Category{}
	err = mysql.Db.Find(&cs).Error
	reply = &pb.Categories{}
	for _, c := range cs {
		pbc := pb.Category{
			ID:       uint32(c.ID),
			Name:     c.Name,
			Problems: []*pb.Problem{},
		}

		ps := []mysql.Problem{}
		mysql.Db.Where(&mysql.Problem{CategoryId: c.ID}).Find(&ps)
		for _, p := range ps {
			pbc.Problems = append(pbc.Problems, &pb.Problem{
				ID:         uint32(p.ID),
				Name:       p.Name,
				CategoryId: uint32(p.CategoryId),
				Content:    p.Content,
				VerifyCode: p.VerifyCode,
			})
		}
		reply.Value = append(reply.Value, &pbc)
	}
	return
}

func (s *server) CreateProblem(ctx context.Context, in *pb.Problem) (reply *pb.Problem, err error) {
	p := mysql.Problem{
		Name:       in.Name,
		CategoryId: uint(in.CategoryId),
		Content:    in.Content,
		VerifyCode: in.VerifyCode,
	}
	mysql.Db.Create(&p)
	reply = &pb.Problem{
		ID:         uint32(p.ID),
		Name:       p.Name,
		CategoryId: uint32(p.CategoryId),
		Content:    p.Content,
		VerifyCode: p.VerifyCode,
	}
	return
}

func (s *server) CreateQuestion(ctx context.Context, in *pb.Question) (reply *pb.Question, err error) {
	q := mysql.Question{
		UserId:    in.UserId,
		Title:     in.Title,
		ProblemId: uint(in.ProblemId),
		Content:   in.Content,
	}
	mysql.Db.Create(&q)
	reply = &pb.Question{
		ID:        uint32(q.ID),
		UserId:    q.UserId,
		ProblemId: uint32(q.ProblemId),
		Title:     q.Title,
		Content:   q.Content,
		Answers:   []*pb.Answer{},
	}
	return
}

func (s *server) CreateAnswer(ctx context.Context, in *pb.Answer) (reply *pb.Answer, err error) {
	q := mysql.Answer{
		QuestionId: uint(in.QuestionId),
		UserId:     in.UserId,
		Content:    in.Content,
	}
	mysql.Db.Create(&q)
	reply = &pb.Answer{
		ID:         uint32(q.ID),
		QuestionId: uint32(q.QuestionId),
		UserId:     q.UserId,
		Content:    q.Content,
	}
	return
}

func (s *server) RemoveQuestion(ctx context.Context, in *pb.IDRequest) (reply *pb.Empty, err error) {
	mysql.Db.Delete(&mysql.Question{}, in.ID)
	return
}

func (s *server) RemoveCategory(ctx context.Context, in *pb.IDRequest) (reply *pb.Empty, err error) {
	mysql.Db.Delete(&mysql.Category{}, in.ID)
	return
}

func (s *server) RemoveProblem(ctx context.Context, in *pb.IDRequest) (reply *pb.Empty, err error) {
	mysql.Db.Delete(&mysql.Problem{}, in.ID)
	return
}

func (s *server) RemoveAnswer(ctx context.Context, in *pb.IDRequest) (reply *pb.Empty, err error) {
	mysql.Db.Delete(&mysql.Answer{}, in.ID)
	return
}
